from uuid import uuid4
import json
import os
from datetime import datetime
from django.db.models import Q

from rest_framework import serializers

from .models import *
from util.exception import ValidationError
from django.conf import settings


class ProductCheckSerializer(serializers.ModelSerializer):
    product_name = serializers.CharField(max_length=200, allow_null=True, allow_blank=True)
    product_number = serializers.CharField(max_length=200, allow_null=True, allow_blank=True)

    class Meta:
        model = ProductModel
        fields = ["product_name", "product_number", ]


class ProductListSerializer(serializers.ModelSerializer):
    class Meta:
        model = ProductModel
        fields = ["id", "product_name", "product_number", ]


class productCreateSerializer(serializers.ModelSerializer):
    product_name = serializers.CharField(max_length=200, allow_null=True, allow_blank=True)
    product_number = serializers.CharField(max_length=200, allow_null=True, allow_blank=True)

    def validate_product_number(self, obj):
        p = ProductModel.objects.filter(product_number=obj).first()
        if p:
            raise ValidationError(20001)
        else:
            return obj

    def create(self, data):
        id = str(uuid4()).replace("-", "")
        data["id"] = id
        ProductModel.objects.create(**data)

    class Meta:
        model = ProductModel
        fields = ["product_name", "product_number", ]


class productUpdateSerializer(serializers.ModelSerializer):
    id = serializers.CharField(max_length=50, allow_null=False, allow_blank=False)
    product_name = serializers.CharField(max_length=200, allow_null=True, allow_blank=True)
    product_number = serializers.CharField(max_length=200, allow_null=True, allow_blank=True)
    is_delete = serializers.BooleanField(allow_null=True)

    class Meta:
        model = ProductModel
        fields = ["id", "is_delete", "product_name", "product_number"]

    def create(self, validated_data):
        data = {}
        for k, v in validated_data.items():
            if v:
                data.update({k: v})
        ProductModel.objects.filter(id=data["id"]).update(**data)
